package br.ita.redecasd.mi.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import static br.ita.redecasd.mi.db.DBConstants.*;

/**
 *
 * @author mi
 */
public class UserDB {

    private Connection connection;
    
    public UserDB() throws ClassNotFoundException, SQLException {
        Class.forName( JDBC_DRIVER );
        connection = DriverManager.getConnection( DATABASE_URL, USERNAME, PASSWORD );
        
    }

    public PrivateKey getUserPrivateKey( String username ) throws SQLException, FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException      {
        String query = "Select keyFile from keyInfo where login = ?";
        PreparedStatement st = connection.prepareStatement( query );
        st.setString(1, username);
        ResultSet rs = st.executeQuery();
        if( rs.next())
        {
                String fileName = rs.getString( "keyFile" );
                File file = new File( fileName );
		if( !file.exists() || !file.canRead() )
			return null;
		//fileName = "/home/mi/TG/certificados/anakin-key.der";
		FileInputStream keyfis = new FileInputStream( fileName );
		byte[] encKey = new byte[keyfis.available()];
		keyfis.read(encKey);
		
                
		KeyFactory kfac = KeyFactory.getInstance( "DSA" );
                PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( encKey );
                
		PrivateKey priv = kfac.generatePrivate(spec);
                
                rs.close();
                st.close();
                
		
		return priv;
        }

        return null;
    }
    
    

}
